<template>
  <div>
    <el-card>
      <el-form ref="formFilter" :model="filter" v-loading="loading" @click="onFilterSubmit">
        <el-form-item prop="name" label="资源名称">
          <el-input v-model="filter.name" />
        </el-form-item>
        <el-form-item prop="categoryId" label="资源分类">
          <el-select v-model="filter.categoryId" >
            <el-option
              v-for="item of categoryItems"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="url" label="资源路径">
          <el-input v-model="filter.url" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onFilterSubmit">筛选</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <div slot="header">
        <el-button @click="handleAdd">添加资源</el-button>
        <el-button @click="$router.push({ name: 'resource-category' })"
          >资源分类</el-button
        >
      </div>
      <el-table :data="items" style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="编号" />
        <el-table-column label="资源名称" prop="name" />
        <el-table-column label="资源路径" prop="url" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="添加时间" prop="createdTime" />
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="handleEdit(scope.row)"
              size="mini"
            >
              编辑
            </el-button>
            <el-button
              @click.native.prevent="handleDelete(scope.row)"
              type="danger"
              size="mini"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="filter.current"
        :page-sizes="[5, 10, 50]"
        :page-size="filter.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <DialogAddOrEdit ref="dialogAdd" />
      <DialogAddOrEdit ref="dialogEdit" :id="editItemId" />
    </el-card>
  </div>
</template>
<script lang="ts">
import Vue from 'vue'
import {
  getAllCategory,
  getResourcePages,
  removeItem
} from '@/services/resource'
import { wrapAsyncWithLoading } from '@/utils/helper'
import DialogAddOrEdit from './components/DialogAddOrEdit.vue'
import { ElForm } from 'element-ui/types/form'
import PromiseDialog from '@/components/PromiseDialog.vue'
import { HasId, ID } from '@/types'
export default Vue.extend({
  name: 'ResourceIndex',
  components: {
    DialogAddOrEdit
  },
  data () {
    return {
      loading: false,
      filter: {
        name: '',
        url: '',
        categoryId: null,
        current: 1, // p:绑定初始？？
        size: 5
      },
      items: [],
      categoryItems: [],
      editItemId: '' as ID,
      total: 0
    }
  },
  created () {
    wrapAsyncWithLoading(this, 'loading', 'loadItems')
    this.loadItems()
  },
  methods: {
    async loadItems () {
      await Promise.all([
        getAllCategory().then(({ data }) => {
          if (data.code === '000000') {
            this.categoryItems = data.data
            return
          }
          throw new Error('加载资源分类失败')
        }),
        getResourcePages(this.filter).then(({ data }) => {
          if (data.code === '000000') {
            this.items = data.data.records
            this.total = data.data.total
            return
          }
          throw new Error('加载资源失败')
        })
      ])
    },
    async handleAdd () {
      try {
        await (this.$refs.dialogAdd as PromiseDialog).open()
      } catch (error) {
        return
      }
      this.$message.success('已添加')
      this.loadItems()
    },
    async handleEdit (item: HasId) {
      this.editItemId = item.id
      // 子组件多久能拿到？
      try {
        await (this.$refs.dialogEdit as PromiseDialog).open()
      } catch (error) {
        if (typeof error === 'string') {
          this.$message.error(error)
          this.loadItems()
        }
        return
      }
      this.$message.success('编辑成功')
      this.loadItems()
    },
    async handleDelete (item: HasId) {
      try {
        await this.$confirm('确认删除分类么')
      } catch (error) {
        return
      }
      const { data } = await removeItem(item.id)
      if (data.code === '000000') {
        this.$message.success('已删除')
        this.loadItems()
      }
    },
    /** 分页 */

    handleSizeChange (size: number) {
      this.filter.size = size
      this.filter.current = 1
      this.loadItems()
    },
    handleCurrentChange (current: number) {
      this.filter.current = current
      this.loadItems()
    },
    onFilterSubmit () {
      this.filter.current = 1
      this.loadItems()
    },
    onReset () {
      (this.$refs.formFilter as ElForm).resetFields()
    }
  }
})
</script>
